package DCSource.PluginsClassLoader;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class PLClassLoader {
	public PLClassLoader(){}
	private ArrayList<Class <?>> list = new ArrayList<Class <?>>();
	public void loadFolder(String folder){
		list.clear();
		try{
			File[] jarFiles = new File(folder).listFiles(new FileFilter() {
		         public boolean accept(File f) {
		            return f.getName().toLowerCase().endsWith(".jar");
		         }
		      });
		 
		      URL[] urls = new URL[jarFiles.length];
		      for(int i=0; i<jarFiles.length; i++) {
		         urls[i] = jarFiles[i].toURI().toURL();
		      }
		 
		      ClassLoader loader = new URLClassLoader(urls);
		 
		      for(File jarFile : jarFiles) {            
		         JarInputStream jaris = new JarInputStream(new FileInputStream(jarFile));
		         JarEntry entry;            
		         while((entry = jaris.getNextJarEntry()) != null) {                
		            if(entry.getName().toLowerCase().endsWith(".class")) {
		               String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
		               Class<?> cls = loader.loadClass(className);
		               list.add(cls);                  
		            }
		         }
		      }
		}catch(Exception err){
		}
	}
	public ArrayList<Class <?>> getFromFile(String file){
		ArrayList<Class <?>> returning =  new ArrayList<Class <?>>();
		try{
		File uri = new File(file);
		URL url = uri.toURI().toURL();
		ClassLoader loader = new URLClassLoader(new URL[]{url});
		JarInputStream jaris = new JarInputStream(new FileInputStream(uri));
        JarEntry entry;            
        while((entry = jaris.getNextJarEntry()) != null) {                
           if(entry.getName().toLowerCase().endsWith(".class")) {
              String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
              Class<?> cls = loader.loadClass(className);
              returning.add(cls);                  
           }
        }
		}catch(Exception err){}
		return returning;
	}
	public ArrayList<Class <?>> toArrayList(){
		return list;
	}
}
